import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { blockchainService } from '../services/blockchain'

/**
 * 钱包连接 Composable
 * 提供钱包状态管理和操作方法
 */
export function useWallet() {
  // 响应式状态
  const isConnected = ref(false)
  const isConnecting = ref(false)
  const currentAccount = ref<string | null>(null)
  const accountBalance = ref<string>('0')
  const networkId = ref<string>('')
  const isCorrectNetwork = ref(true)
  const contractsInitialized = ref(false)

  // 计算属性
  const shortAddress = computed(() => {
    if (!currentAccount.value) return ''
    return `${currentAccount.value.slice(0, 6)}...${currentAccount.value.slice(-4)}`
  })

  const networkStatus = computed(() => {
    return isCorrectNetwork.value ? '✅ 正确网络' : '❌ 网络错误'
  })

  const networkStatusColor = computed(() => {
    return isCorrectNetwork.value ? 'success' : 'error'
  })

  const isReady = computed(() => {
    return isConnected.value && isCorrectNetwork.value && contractsInitialized.value
  })

  /**
   * 初始化钱包
   */
  async function initWallet() {
    try {
      console.log('🔄 初始化钱包...')
      
      // 初始化 Web3
      await blockchainService.init()
      
      // 检查是否已连接
      const account = await blockchainService.getCurrentAccount()
      if (account) {
        currentAccount.value = account
        isConnected.value = true
        await loadAccountInfo()
        await initContracts()
      }
      
      // 检查网络
      await checkNetwork()
      
      console.log('✅ 钱包初始化完成')
      return true
    } catch (error) {
      console.error('❌ 钱包初始化失败:', error)
      return false
    }
  }

  /**
   * 连接钱包
   */
  async function connectWallet() {
    if (isConnecting.value) return false
    
    isConnecting.value = true
    
    try {
      console.log('🔗 连接钱包...')
      
      // 连接 MetaMask
      const account = await blockchainService.connectWallet()
      currentAccount.value = account
      isConnected.value = true
      
      // 加载账户信息
      await loadAccountInfo()
      
      // 检查网络
      await checkNetwork()
      
      // 初始化合约
      if (isCorrectNetwork.value) {
        await initContracts()
      }
      
      message.success(`钱包连接成功！账户: ${shortAddress.value}`)
      console.log('✅ 钱包连接成功:', account)
      
      return true
    } catch (error: any) {
      console.error('❌ 钱包连接失败:', error)
      
      if (error.code === 4001) {
        message.error('用户拒绝了连接请求')
      } else if (error.code === -32002) {
        message.error('连接请求已存在，请检查 MetaMask')
      } else {
        message.error(`连接失败: ${error.message || '未知错误'}`)
      }
      
      return false
    } finally {
      isConnecting.value = false
    }
  }

  /**
   * 断开钱包连接
   */
  function disconnectWallet() {
    currentAccount.value = null
    accountBalance.value = '0'
    isConnected.value = false
    networkId.value = ''
    isCorrectNetwork.value = true
    contractsInitialized.value = false
    
    message.info('钱包已断开连接')
    console.log('🔌 钱包已断开连接')
  }

  /**
   * 加载账户信息
   */
  async function loadAccountInfo() {
    if (!currentAccount.value) return
    
    try {
      console.log('📊 加载账户信息...')
      
      // 获取余额
      const balance = await blockchainService.getBalance(currentAccount.value)
      accountBalance.value = parseFloat(balance).toFixed(4)
      
      // 获取网络信息
      await checkNetwork()
      
      console.log('✅ 账户信息加载完成')
    } catch (error) {
      console.error('❌ 加载账户信息失败:', error)
    }
  }

  /**
   * 检查网络
   */
  async function checkNetwork() {
    try {
      const web3 = blockchainService.getWeb3()
      const currentNetworkId = await web3.eth.net.getId()
      const expectedNetworkId = import.meta.env.VITE_NETWORK_ID || '20241214'
      
      // 将 BigInt 或 Number 转换为字符串
      const currentNetworkIdStr = String(currentNetworkId)
      networkId.value = currentNetworkIdStr
      isCorrectNetwork.value = currentNetworkIdStr === expectedNetworkId
      
      if (!isCorrectNetwork.value) {
        console.warn(`⚠️ 网络 ID 不匹配，期望 ${expectedNetworkId}，实际 ${currentNetworkIdStr}`)
      }
      
      console.log('🌐 网络检查完成:', { networkId: currentNetworkIdStr, expectedNetworkId })
    } catch (error) {
      console.error('❌ 网络检查失败:', error)
      isCorrectNetwork.value = false
    }
  }

  /**
   * 切换网络
   */
  async function switchNetwork() {
    if (!isCorrectNetwork.value && (window as any).ethereum) {
      try {
        const expectedNetworkId = import.meta.env.VITE_NETWORK_ID || '20241214'
        
        await (window as any).ethereum.request({
          method: 'wallet_switchEthereumChain',
          params: [{ chainId: `0x${parseInt(expectedNetworkId).toString(16)}` }],
        })
        
        await checkNetwork()
        
        if (isCorrectNetwork.value) {
          await initContracts()
        }
        
        message.success('网络切换成功')
        return true
      } catch (error: any) {
        if (error.code === 4902) {
          // 网络不存在，添加网络
          try {
            await (window as any).ethereum.request({
              method: 'wallet_addEthereumChain',
              params: [{
                chainId: `0x${parseInt(import.meta.env.VITE_NETWORK_ID || '20241214').toString(16)}`,
                chainName: 'FamilyChain',
                rpcUrls: [import.meta.env.VITE_WEB3_RPC_URL || 'http://localhost:8545'],
                nativeCurrency: {
                  name: 'ETH',
                  symbol: 'ETH',
                  decimals: 18,
                },
              }],
            })
            
            await checkNetwork()
            
            if (isCorrectNetwork.value) {
              await initContracts()
            }
            
            message.success('网络添加成功')
            return true
          } catch (addError) {
            console.error('❌ 添加网络失败:', addError)
            message.error('添加网络失败，请手动添加')
            return false
          }
        } else {
          console.error('❌ 切换网络失败:', error)
          message.error('切换网络失败')
          return false
        }
      }
    }
    return false
  }

  /**
   * 初始化合约
   */
  async function initContracts() {
    try {
      console.log('📋 初始化智能合约...')
      
      await blockchainService.initContracts()
      contractsInitialized.value = true
      
      console.log('✅ 智能合约初始化完成')
      return true
    } catch (error) {
      console.error('❌ 智能合约初始化失败:', error)
      contractsInitialized.value = false
      return false
    }
  }

  /**
   * 刷新账户信息
   */
  async function refreshAccount() {
    if (isConnected.value) {
      await loadAccountInfo()
      message.success('账户信息已刷新')
    }
  }

  /**
   * 获取合约实例
   */
  function getContract(contractType: 'registry' | 'governance' | 'nft') {
    if (!contractsInitialized.value) {
      throw new Error('合约未初始化')
    }
    
    switch (contractType) {
      case 'registry':
        return blockchainService.getRegistryContract()
      case 'governance':
        return blockchainService.getGovernanceContract()
      case 'nft':
        return blockchainService.getNFTContract()
      default:
        throw new Error(`未知的合约类型: ${contractType}`)
    }
  }

  // 自动初始化
  onMounted(async () => {
    await initWallet()
    
    // 监听账户变化
    if ((window as any).ethereum) {
      try {
        (window as any).ethereum.on?.('accountsChanged', async (accounts: string[]) => {
          if (accounts.length === 0) {
            disconnectWallet()
          } else if (accounts[0] !== currentAccount.value) {
            currentAccount.value = accounts[0]
            await loadAccountInfo()
            if (isCorrectNetwork.value) {
              await initContracts()
            }
            message.info(`账户已切换: ${shortAddress.value}`)
          }
        })
        
        // 监听网络变化
        (window as any).ethereum.on?.('chainChanged', async (chainId: string) => {
          const newNetworkId = parseInt(chainId, 16).toString()
          networkId.value = newNetworkId
          isCorrectNetwork.value = newNetworkId === (import.meta.env.VITE_NETWORK_ID || '20241214')
          
          if (isCorrectNetwork.value) {
            await initContracts()
            message.success('网络已切换')
          } else {
            contractsInitialized.value = false
            message.warning('请切换到正确的网络')
          }
        })
      } catch (error) {
        console.log('⚠️ MetaMask 事件监听设置失败:', error)
      }
    }
  })

  return {
    // 状态
    isConnected,
    isConnecting,
    currentAccount,
    accountBalance,
    networkId,
    isCorrectNetwork,
    contractsInitialized,
    
    // 计算属性
    shortAddress,
    networkStatus,
    networkStatusColor,
    isReady,
    
    // 方法
    initWallet,
    connectWallet,
    disconnectWallet,
    loadAccountInfo,
    checkNetwork,
    switchNetwork,
    initContracts,
    refreshAccount,
    getContract,
  }
}

